package
{
	import com.chris.homecare.AppScreen;
	import com.chris.homecare.data.DataUtil;
	import com.chris.homecare.data.FetchRemoteData;
	import com.chris.homecare.utils.ShowNativeAlert;
	
	import flash.desktop.NativeApplication;
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.StatusEvent;
	import flash.events.TimerEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	import flash.utils.Timer;
	
	import air.net.URLMonitor;
	
	import pl.mateuszmackowiak.nativeANE.events.NativeDialogEvent;
	
	import starling.core.Starling;
	
	[SWF(frameRate="30")]
	public class HomeCare extends Sprite
	{
		private var _starling:Starling;
		private var urlmonitor:URLMonitor;
		private var myURL:URLRequest = new URLRequest("http://speiusscare.co.uk/sitterApp");
		private var dataRecevierTimer:Timer;
		private var currentPage:String;

		private var launchImage:Loader;
		private var splashSreenTimer:Timer;
		
		public function HomeCare()
		{
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			
			NativeApplication.nativeApplication.addEventListener(Event.EXITING, exitHandler);
			
			this.loaderInfo.addEventListener(Event.COMPLETE, loaderInfo_completeHandler);
			DataUtil.createDB();
		}
		
		private function showSplashScreen():void
		{
			var file:File = File.applicationDirectory.resolvePath("assets/images/background.png");
			if(file.exists)
			{
				var bytes:ByteArray = new ByteArray();
				var stream:FileStream = new FileStream();
				stream.open(file, FileMode.READ);
				stream.readBytes(bytes, 0, stream.bytesAvailable);
				stream.close();
				launchImage = new Loader();
				launchImage.contentLoaderInfo.addEventListener(Event.COMPLETE, onLaunchImageComplete);
				launchImage.loadBytes(bytes);
				this.addChild(launchImage);
			}
		}
		
		protected function onLaunchImageComplete(event:Event):void
		{
			var ratio:Number;
			
			var bit:Bitmap = launchImage.content as Bitmap
			bit.smoothing = true
			
			if((stage.stageWidth - launchImage.content.width) < (stage.stageHeight - launchImage.content.height))
			{
				ratio = stage.stageHeight/launchImage.content.height;
				launchImage.content.height = stage.stageHeight;
				launchImage.content.width *= ratio;
				launchImage.x = (stage.stageWidth - launchImage.content.width)/2;
			}
			
			else
			{
				ratio = stage.stageWidth/launchImage.content.width;
				launchImage.content.width = stage.stageWidth;
				launchImage.content.height *= ratio;
				launchImage.y = (stage.stageHeight - launchImage.content.height)/2;
			}
		}
		
		protected function loaderInfo_completeHandler(event:Event):void
		{
			showSplashScreen();
			
			Starling.handleLostContext = true;
			Starling.multitouchEnabled = true;
			this._starling = new Starling(AppScreen, this.stage);
			this._starling.enableErrorChecking = false;
			
			this.stage.addEventListener(Event.RESIZE, stage_resizeHandler, false, int.MAX_VALUE, true);
			this.stage.addEventListener(Event.DEACTIVATE, stage_deactivateHandler, false, 0, true);
			this._starling.addEventListener("rootCreated", starling_rootCreatedHandler);
			this._starling.start();
			
			myURL.method = "HEAD";
			urlmonitor = new URLMonitor(myURL);
			urlmonitor.addEventListener(StatusEvent.STATUS, on_Connection);
			urlmonitor.start();
		}
		
		private function starling_rootCreatedHandler():void
		{
			splashSreenTimer = new Timer(200, 1);
			splashSreenTimer.addEventListener(TimerEvent.TIMER, onSplashScreenTimerComplete);
			splashSreenTimer.start();
		}
		
		protected function onSplashScreenTimerComplete(event:TimerEvent):void
		{
			splashSreenTimer.stop();
			splashSreenTimer.removeEventListener(TimerEvent.TIMER, onSplashScreenTimerComplete);
			splashSreenTimer = null;
			this.removeChild(this.launchImage);
			this.launchImage.unloadAndStop(true);
			this.launchImage = null;
		}
		
		private function stage_resizeHandler(event:Event):void
		{
			this._starling.stage.stageWidth = this.stage.stageWidth;
			this._starling.stage.stageHeight = this.stage.stageHeight;
			
			const viewPort:Rectangle = this._starling.viewPort;
			viewPort.width = this.stage.stageWidth;
			viewPort.height = this.stage.stageHeight;
			try
			{
				this._starling.viewPort = viewPort;
			}
			catch(error:Error) {}
		}
		
		private function stage_deactivateHandler(event:Event):void
		{
			this._starling.stop();
			this.stage.addEventListener(Event.ACTIVATE, stage_activateHandler, false, 0, true);
		}
		
		private function stage_activateHandler(event:Event):void
		{
			this.stage.removeEventListener(Event.ACTIVATE, stage_activateHandler);
			this._starling.start();
		}
		
		protected function exitHandler(event:Event):void
		{
			event.preventDefault();
		}
		
		protected function on_Connection(event:Event):void
		{
			if(event.target.available == true)
			{
				currentPage = "Business";
				dataRecevierTimer = new Timer(200, 7);
				dataRecevierTimer.addEventListener(TimerEvent.TIMER, onTimerComplete);
				dataRecevierTimer.start();
				
				//FetchRemoteData.getClient().getBusinessPageData();
				
				urlmonitor.removeEventListener(StatusEvent.STATUS, on_Connection);
				urlmonitor.stop();
			}
			
			else
			{
				var alertObject:Object = new Object();
				alertObject.message = "Please connect to internet \n to receive the latest data";
				alertObject.title = "Speiuss";
				alertObject.buttons = Vector.<String>(["OK"]);
				ShowNativeAlert.showAlert(alertObject);
			}
		}
		
		public function alertResponse(event:NativeDialogEvent):void
		{
			trace("alertResponse");
		}
		
		protected function onTimerComplete(event:TimerEvent):void
		{
			switch(currentPage)
			{
				case "Business":
				{
					FetchRemoteData.getClient().populateJobPosition();
					currentPage = "jobPosition";
					break;
				}
					
				case "jobPosition":
				{
					FetchRemoteData.getClient().pouplateTeamListData();
					currentPage = "TeamList";
					break;
				}
					
				case "TeamList":
				{
					FetchRemoteData.getClient().populateReviewData();
					currentPage = "reviewData";
					break;
				}
					
				case "reviewData":
				{
					FetchRemoteData.getClient().pouplateUpdatesListData();
					currentPage = "updatesList";
					break;
				}
					
				case "updatesList":
				{
					FetchRemoteData.getClient().populateOurServices();
					currentPage = "ourServices";
					break;
				}
					
				case "ourServices":
				{
					FetchRemoteData.getClient().populateJobListData();
					currentPage = "jobList";
					break;
				}
					
				case "jobList":
				{
					FetchRemoteData.getClient().populateEvents();
					currentPage = "eventsData";
					break;
				}
					
				default:
				{
					break;
				}
			}
		}
	}
}